package cn.gl.basic.controller;

import cn.gl.basic.util.AjaxResult;
import cn.gl.basic.util.FastDfsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


/**
 * 上传 - 需要【请求方式：post】
 * 下载 - 不需要
 * 删除 - 需要【请求方式：delete】
 * 修改 - 不需要 = 先删除再上传
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    //@RequestPart对复杂表单项的处理，默认name="file",与上传文件的name属性值一致
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){

        try {
            //System.out.println(file.getOriginalFilename() + ":" + file.getSize());
            String originalFilename = file.getOriginalFilename();
            //xxx.jpg
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            //工具类返回的完整路径：/goup1/xxxxx/yyyy
            String filePath =  FastDfsUtils.upload(file.getBytes(), extName);
            return AjaxResult.me().setObj(filePath); //把上传后的路径返回回去
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("上传失败!"+e.getMessage());
        }
    }

    /**
     * 参数：完整路径 /group1/xxxxx/yyyy
     * 返回值：成功与否，还要返回地址
     */
    @DeleteMapping
    public AjaxResult del(@RequestParam(required = true,value = "path") String path){
        try {
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); // group1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// xxxxx/yyyy

            //System.out.println(groupName);//获取组名
            //System.out.println(remotePath);//远程路径
            FastDfsUtils.delete(groupName, remotePath);
            return  AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("删除失败!"+e.getMessage());
        }
    }
}